import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
//使用原子类实现线程安全
public class Test {
    //不使用原生的int 而是替换成AtomicInteger
    //private static int count = 0;
    private static AtomicInteger count = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 100000; i++) {
                //count++;
                count.getAndIncrement();//count++(通过CAS方式实现;未加锁更高效)
                //count.incrementAndGet();//++count
                //count.getAndAdd(n); //count+=n
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 200000; i++) {
                count.getAndIncrement();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count="+count.get());
    }
}
